package com.hhxy.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ghp
 * @date 2023/2/26
 * @title 延迟队列配置类（基于插件实现延迟队列）
 * @description
 */
@Configuration
public class DelayedQueueConfig {
    // 延迟队列
    public static final String DELAYED_QUEUE = "delayed.queue";
    // 延迟交换机
    public static final String DELAYED_EXCHANGE = "delayed.exchange";
    // 交换机的路由键
    public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";
    // 延迟交换机的类型（延迟插件提供的固定写法，专门用来设置延迟交换机）
    public static final String DELAYED_EXCHANGE_TYPE = "x-delayed-message";


    /**
     * 声明延迟队列
     */
    @Bean
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE);
    }


    /**
     * 声明延迟交换机
     */
    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> arguments = new HashMap<>();
        // 设置延迟交换机的的路由方式
        arguments.put("x-delayed-type", "direct");
        /*
            1. 交换机的名称
            2. 交换机的类型
            3. 交换机是否持久化，true表示持久化
            4. 交换机是否需要自动删除，true表示需要自动删除
            5. 其它参数
         */
        return new CustomExchange(DELAYED_EXCHANGE, DELAYED_EXCHANGE_TYPE, true, false, arguments);
    }

    /**
     * 延迟队列 delayedQueue 绑定延迟交换机 delayedExchange
     */
    @Bean
    public Binding delayedQueueBindingDelayedExchange(@Qualifier("delayedQueue") Queue delayedQueue,
                                                      @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}